/*
 * Contact sync functions
 * http://strintwebapps.com/
 *
 * Copyright (c) 2009 SprintWebapps.com
 * Dual licensed under the MIT and GPL licenses.
 * Revision: 0
 */
var DEBUG = false;
var _services = new Array();
var _contacts = new Array();
var _current_service = '';


/******HELPER**********/
Array.prototype.size = function () {
    var l = this.length ? --this.length : -1;
    for (var k in this) {
    l++;
    }
    return l;
}
var _captcha = 0;
$.ajaxSetup({ 
    error: function(xhr, status, err) { 
         if(xhr.status==403){
            _captcha = 1;
            $('#d_captcha').show();
            var img = eval('('+xhr.responseText+')');
            $('#i_captcha').attr('src',img.captcha_url);
            $('#captcha_token').val(img.captcha_token);
         }else{
             error(xhr.responseText);
         }
         loading('');
    } 
}); 

function new_login(service) {
	$('#d-login-service').html(service)
	$('#d-login').dialog('open', {
		'modal' : true,
	});
	_current_service = service;

}
function do_login() {	
    // get
	user = $('#user').val();
	pass = $('#pass').val();
    if(_captcha && !$('#catcha_respose').val()) 
        error('Complete captcha');    
	// validate
    else if(!$('#user_form').valid()){
        error('Complete user and password');            
    }
	// call
	new_service(_current_service, user, pass);
    
}

function new_service(service, user, pass) {
    loading('connecting...');	
	if (!(service in _services)|| _captcha) {
		_services[service] = new Service(service, "tmpl-service-column", user,
				pass);
       
		_services[service].get_contacts(function() {
			show_service(service);
		});
	}else{
        $('#d-login').dialog('close');
    }
}
function show_service(s) {
	_services[s].draw();
}

function msg(m) {
	el = $('#msg').attr('class', '');
	el.html(m);
	if (m == '') {
		el.hide();
	} else {
		el.show().effect('highlight');
	}

}
function loading(m) {
	el = $('#loading');
	el.html(m);
	if (m == '') {
		el.hide();
	} else {
		el.show();
	}
}
function error(m) {
	msg(m);
	$('#msg').addClass('error');
}

_api_url = '/';

function read_data(model, callback) {
	loading('cargando...');
	url = _api_url + model + '';
	// url = 'js/ej-data-contacts.js';
	$.getJSON(url, function(res, status) {
		loading('');
		if (status == 'error') {
			error('Server error ');
		} else {
            $('#d-login').dialog('close');
			callback(res);
		}
	});
}

/** ****** Class ****** */

function Service(name, template, user, pass) {
	var manage = this;
	this.name = name;
	this.template = template;
	this.user = user;
	this.pass = pass;
	this.contacts = [];
	this.get_contacts = function(callback) {
        var captcha = '';    
        if(_captcha)
            captcha = '&captcha_token='+$('#captcha_token').val()+'&captcha_response='+$('#captcha_response').val();
		if (DEBUG)
			url = 'statics/test-js/' + this.name + '-contact.js';
		else
			url = 'contacts/' + this.name + '/?username=' + this.user
					+ '&password=' + this.pass + captcha
		read_data(url, function(res) {
			manage.contacts = res;
			if (typeof (callback) != 'undefined') {
                _captcha = 0;
                $('#d_captcha').hide();
				callback();
			}
		});
	};
	this.draw = function() {
		loading('drawing...');                
        
        if(_services.size()==1)
            do_main_template(this.contacts, this.name);
        else
            do_match_template(this.contacts, this.name);


	};
    

}
var drag_opt = {opacity:	0.5, helper:'clone'	,revert: 'invalid',cursor: 'move'};
function do_main_template(data, service) {

	list = '';
	for ( var i in data) {
        _contacts[i] = data[i]
		list += '<li id="contact-' + data[i].id + '" class="bg2 main-contact" >';
		row = do_contact_box(data[i]);
        row += do_service_box(data[i],service)
		list += row + '</li>';
	}
	$('#result').append(list);
    $(".main-contact").droppable({ accept: '.service-box' , hoverClass:'container-hover',
         drop: function(event, ui) { 
                $el = $(ui.draggable);
                $(this).append($el);
            }
        });
    $(".service-box").draggable(drag_opt);

}

function do_match_template(data,service) {
	for ( var i in data) {
		contact = data[i];
		// search
		match_id = 0;
		for ( var j in _contacts ) {
			g_contact = _contacts[j];
			if ((g_contact.name != '' && g_contact.name == contact.name ) ){
                //||(g_contact.email == contact.email )) {
				match_id = g_contact.id;
                break;
			}
		}
		// draw
		box = do_service_box(data[i], service);
		// insert
		if (match_id != 0) {
			$('#contact-' + match_id).append(box);
		} else {
			$('#free').append('<li>' + box + '</li>')
            
		}     
        
        $(".service-box").draggable(drag_opt);
	}

}

function do_data_box(data, tooltip){
    content='<div class="contact-data">'
    thumb = '<img class="thumb" src="/statics/images/user.gif" alt="'+data['name']+'" />';
	for ( var key in data) {
		if( key=='thumb'){
            thumb = '<img width="48" height="48" class="thumb" src="'+data['thumb']+'" alt="'+data['name']+'" />';           
	    }else{ if( key!='id')
		    	content += key + ":<span>" + data[key] + "</span> <br />";
        }
	}
    content += '</div>';
    return  '<div class="contact-box '+tooltip+'">'+thumb + content +'</div>';
}
function do_contact_box(data) {    
	row = '<div class="contact" >' +do_data_box(data) + '</div>';
	return row;
}

function do_service_box(data,service){
    return '<div class="service-box '+service+'" id="'+service+'-' + data.id + '">'+do_data_box(data, 'tooltip')+'</div>';
}
